(** 
    Utils.ml
    A general library for the project. You will find i/o operations functions,
    global variables and useful functions. See mlib.mli for more details.

    Bozman Çagdas <bozman.cagdas@gmail.com> - 2011
    Razakamiadana Tefin <tefy.razaka@gmail.com>   - 2011
*)

(* Set the flag to true if you want to activate the debug mode *)
let debug_flag = ref true

let debug fmt = 
  if !debug_flag then Printf.eprintf fmt 
  else Printf.ifprintf stderr fmt

let spf = Printf.sprintf

let from_group s index = 
  try (Str.matched_group index s) with Invalid_argument _ -> ""

let read in_ch = 
  try Some (input_line in_ch) with End_of_file -> None

let write = output_string

let open_in_file input_filename = 
  try open_in input_filename 
  with Sys_error _ -> failwith (spf "Cannot open the file %s" input_filename)

let open_out_file output_filename = 
  try open_out output_filename 
  with Sys_error _ -> failwith (spf "Cannot open the file %s" output_filename)

let t_reg = Str.regexp ".*&#\\([0-9]+\\);.*"
  
let special = Str.regexp "&#[0-9]+;"

let amp = Str.regexp "&amp;"

let soc s =
  let size = String.length s in
  let ss = String.sub s 2 (size - 3) in
  let with_escape = Char.escaped (char_of_int (int_of_string ss)) in
  String.sub with_escape 1 (String.length with_escape - 1)

let replace_all r f = 
  Str.global_substitute r (fun s -> f (Str.matched_string s))

let format_title s =
  let space = Str.regexp "[ ]" in
  let l = Str.split space s in
  let s = replace_all special soc (String.concat "%20" l) in
  Str.global_replace amp "%26" s

let list_of_req reqs =   
  let rec aux accu = function  
    | Ast.RSimpl c -> c :: accu      
    | Ast.RMult (c, next) -> aux (c :: accu) next
  in
  aux [] reqs

let ignore = 
  Str.regexp "[A|a]ide:.*\\|[P|p]rojet:.*\\|[W|w]ikipédia:.*\\|[P|p]ortail:.*\\|[M|m]odèle:.*\\|[D|d]iscussion[ |_]utilisateur:.*"
